package com.mybatis.sp.mybatisexamle_xml.aop;

import com.mybatis.sp.mybatisexamle_xml.datasourcecong.DynamicDataSourceContextHolder;
import com.mybatis.sp.mybatisexamle_xml.datasourcecong.DatasourceType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Order(-10) // 加上后会先切换数据源在切换事物
@Slf4j
@Aspect
@Component
public class DataSourceAspect {

    @Pointcut("@annotation(com.mybatis.sp.mybatisexamle_xml.aop.DataSource)")
    public void logPointCut() {}

    @Around("logPointCut()")
    public Object beforeDataSource (ProceedingJoinPoint point) {
        MethodSignature methodSignature = (MethodSignature)point.getSignature();
        Method method = methodSignature.getMethod();
        DataSource dataSource;
        Object proceed;
        try {
            dataSource = (DataSource) method.getAnnotation(DataSource.class);
            if(dataSource == null) {
                log.info("数据源类型空值");
                DynamicDataSourceContextHolder.setContextKey(DatasourceType.master);
                proceed = point.proceed();
                log.info("执行后的返回值： {}", proceed);
            } else  {
                DatasourceType value = dataSource.value();
                DynamicDataSourceContextHolder.setContextKey(value);
                log.info("当前使用的数据源为： {}", value);
                proceed = point.proceed();
                log.info("执行后的返回值： {}", proceed);
            }
        } catch (Throwable throwable) {
            log.error("切换失败");
            proceed = throwable.toString();
        }
        return proceed;
    }

    @After("logPointCut()")
    public void afterDataSource () {
        DynamicDataSourceContextHolder.removeContextKey();
    }
}